<?php

declare(strict_types=1);

namespace App\Service;
use App\Model\Guestbook as GuestbookModel;
use Hyperf\Cache\Annotation\Cacheable;

class Guestbook 
{
    /**
     * @Cacheable(prefix="guestbook:count", ttl=60)
     */
    public function countAll() 
    {
        return GuestbookModel::query()->count();
    }

    /**
     * @Cacheable(prefix="guestbook:list", ttl=60, value="#{page}_#{pageSize}")
     */
    public function listRecent($page = 1, $pageSize = 10) 
    {
        $guestbookList = GuestbookModel::query()->orderBy('created_at', 'desc')->take($pageSize)->offset(($page - 1) * $pageSize)->get();
        return $guestbookList;
    }

    public function postNew($userName, $message) 
    {
        $guestbook = new GuestbookModel();
        $guestbook->username = $userName;
        $guestbook->message = $message;
        return $guestbook->save();
    }
}

